package com.lidx.back.statistics.security;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.lidx.back.statistics.commons.SpringContextHolder;
import com.lidx.back.statistics.entity.Role;
import com.lidx.back.statistics.entity.SysUser;
import com.lidx.back.statistics.service.ISysUserService;
import com.lidx.back.statistics.service.impl.SysUserServiceImpl;
import com.lidx.back.statistics.utils.UserUtils;

/**
 * 系统安全认证实现类
 * @author ThinkGem
 * @version 2013-5-29
 */
@Service
//@DependsOn({"sysUserDaoImpl"})
public class SystemAuthorizingRealm extends AuthorizingRealm {

	//@Autowired
	private ISysUserService userService;
	/**
	 * 获取系统业务对象
	 */
	public ISysUserService getSystemService() {
		if (userService == null){
			userService = SpringContextHolder.getBean(SysUserServiceImpl.class);
		}
		return userService;
	}
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		Principal principal = (Principal) getAvailablePrincipal(principals);
		SysUser user = getSystemService().getUserByLoginName(principal.getLoginName());
		
		/*if (user != null) {
			UserUtils.putCache("user", user);
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			//List<Menu> list = UserUtils.getMenuList();
			for (Menu menu : list){
				if (StringUtils.isNotBlank(menu.getPermission())){
					// 添加基于Permission的权限信息
					for (String permission : StringUtils.split(menu.getPermission(),",")){
						info.addStringPermission(permission);
					}
				}
			}
			// 更新登录IP和时间
			//getSystemService().updateUserLoginInfo(user.getId());
			return info;
		} else {
			return null;
		}*/
		if (user != null){
			UserUtils.putCache("user", user);
			String username =  user.getLoginName();
			List<Role> roles =getSystemService().getUserRolesByUserName(username);
			
			 List<String> permissions = Lists.newArrayList();
		     if (roles != null) {  
		    	 for(Role role : roles){
		    		 permissions.add(role.getId().toString());  
		    	 }
		     }  
	        // 查到权限数据，返回授权信息(要包括 上边的permissions)  
	        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();  
	        // 将上边查询到授权信息填充到simpleAuthorizationInfo对象中  
	        simpleAuthorizationInfo.addRoles(permissions);
	        simpleAuthorizationInfo.addStringPermissions(permissions); 
	        getSystemService().updateUserLoginInfo(user.getId());
	        return simpleAuthorizationInfo;
		}else{
			throw new AuthorizationException();
		}
		
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		SysUser user = null;
		/*Subject currentUser = SecurityUtils.getSubject(); 
		currentUser.login(token);*/
		try{
			if(StringUtils.isEmpty(token.getUsername()) || StringUtils.isEmpty(token.getPassword().toString())){
				throw new AuthenticationException("username and password can not be null~");  
				//throw new RuntimeException("username and password can not be null~");
			}
			user = getSystemService().getUserByLoginName(token.getUsername());
			String password = new String(token.getPassword());
			if(!user.getPassword().equals(password)){
				throw new IncorrectCredentialsException("password not correct!");
			}
		}catch(Exception e){
			e.printStackTrace();
			 throw new AuthenticationException();
		}
		if (user != null) {
			//byte[] salt = Encodes.decodeHex(user.getPassword().substring(0,16));
			byte[] salt = user.getPassword().getBytes();
//			return new SimpleAuthenticationInfo(new Principal(user), 
//					user.getPassword().substring(16), ByteSource.Util.bytes(salt), getName());
			return new SimpleAuthenticationInfo(new Principal(user), 
					user.getPassword(), ByteSource.Util.bytes(salt), getName());
		} else {
			throw new UnknownAccountException();
		}
	}

	
	/**
	 * 授权用户信息
	 */
	public static class Principal implements Serializable {

		private static final long serialVersionUID = 1L;
		
		private Integer id;
		private String loginName;
		private String name;
		private Map<String, Object> cacheMap;

		public Principal(SysUser user) {
			this.id = user.getId();
			this.loginName = user.getLoginName();
			this.name = user.getName();
		}

		public Integer getId() {
			return id;
		}

		public String getLoginName() {
			return loginName;
		}

		public String getName() {
			return name;
		}

		public Map<String, Object> getCacheMap() {
			if (cacheMap==null){
				cacheMap = new HashMap<String, Object>();
			}
			return cacheMap;
		}

	}
}
